//
//  themeDetailsViewController.m
//  UI_HLJ_Frame
//
//  Created by dlios on 15-7-3.
//  Copyright (c) 2015年 毕宏伟. All rights reserved.
//

#import "themeDetailsViewController.h"
#import "themeDetailsModel.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "themeDetailsCell.h"
#import "Web_themeViewController.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface themeDetailsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,click>
@property(nonatomic,retain)UIImageView * backimage;
@property(nonatomic,retain)NSMutableArray *themePicarr;
@property(nonatomic,retain)UICollectionView *collectionView;
@property(nonatomic,retain)UILabel * labelTitle;
@property(nonatomic,retain)UILabel * labelDec;
@property(nonatomic ,retain)NSString * weburl;

@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, assign)BOOL isArchiver;

@property(nonatomic, retain)themeDetailsModel *theme;


@end

@implementation themeDetailsViewController

- (void)dealloc
{
    [_collectionView  release];
    [_backimage release];
    [_themePicarr release];
    [_labelDec release];
    [_labelTitle release];
    [_weburl release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 建立反归档
    [self fanguidang];
    
    
    //设置背景图
    self.backimage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    
  //介绍/描述标签
    self.labelTitle = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH / 18.75, HEIGHT / 5, WIDTH / 1.25, HEIGHT / 7.5)];
    self.labelTitle.text= self.title;
    self.labelTitle.textColor= [UIColor redColor];
  
    self.labelDec = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH / 18.75, HEIGHT / 4.15, WIDTH / 1.56, HEIGHT / 3)];
    self.labelDec.text = self.Desc;
    self.labelDec.textColor= [UIColor colorWithRed:0.246 green:0.223 blue:0.873 alpha:1.000];
    self.labelDec.numberOfLines=0;
    self.labelDec.font = [UIFont systemFontOfSize:12];
    

   
    
    
    
    [self.view addSubview:self.backimage];
    
    [self.backimage sd_setImageWithURL:[NSURL URLWithString:self.bkgimage]];
    [self createDATA];
    [self createView];

}

-(void)createView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width / 1.2, self.view.frame.size.height / 1.47);
    //设置最小的行间距
    flowLayout.minimumLineSpacing = 20;
    //设置最小的列间距
    flowLayout.minimumInteritemSpacing = 10;
    //滑动的方向,默认是垂直滑动
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 靠近屏幕边缘的距离
    //    flowLayout.sectionInset = UIEdgeInsetsMake(00, 0, 400, 0);
    

    // 水平滑动设置宽度
        flowLayout.headerReferenceSize = CGSizeMake(300, 1500);
    
     self.themePicarr= [NSMutableArray array];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT / 12, self.view.frame.size.width, self.view.frame.size.height / 1.5) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor=[UIColor colorWithRed:1.000 green:0.997 blue:0.977 alpha:000];
//    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator=NO;

       [self.collectionView release];
    [self.collectionView registerClass:[themeDetailsCell class] forCellWithReuseIdentifier:@"themeDetailsCell"];
    //    [self.collectionView reloadData];
    [self.collectionView addSubview:self.labelTitle];
    [self.collectionView addSubview:self.labelDec];
    [self.view addSubview:self.collectionView];

    
    
    

}
-(void)createDATA{
    
//    

        NSString *url = [NSString stringWithFormat:@"http://hunliji.com/subjects/%@.json?user_id=981817",self.bid];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]init];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"%@", self.bid);
        
        NSDictionary *dic = responseObject;
        NSMutableArray  *arr = [NSMutableArray array];
        arr = dic[@"products"];
     
        for (NSDictionary *tempdic in arr) {
            self.theme = [[themeDetailsModel alloc]init];
            [self.theme setValuesForKeysWithDictionary:tempdic];
            [self.themePicarr addObject:self.theme];
        }
        

        [self.collectionView reloadData];
//        [self.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
}



-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.themePicarr.count;
}
//
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    themeDetailsCell *myCell=[collectionView dequeueReusableCellWithReuseIdentifier:
                       @"themeDetailsCell" forIndexPath:indexPath];
//    [myCell setBackgroundColor:[UIColor whiteColor]];


    self.theme  = [[themeDetailsModel alloc]init];
    self.theme = self.themePicarr[indexPath.row];
    
    myCell.delegatey = self;
    
    [myCell.myImageView sd_setImageWithURL:[NSURL URLWithString:self.theme.photo_path]];
    myCell.mylabel.text = self.theme.subject_desc;
    NSLog(@"%@", self.theme.subject_desc);

    themeDetailsModel *theme  = [[themeDetailsModel alloc]init];
    theme = self.themePicarr[indexPath.row];
   [myCell.myImageView sd_setImageWithURL:[NSURL URLWithString:theme.photo_path] placeholderImage:[UIImage imageNamed:@"占位图"]];
//    [myCell.myImageView sd_setImageWithURL:[NSURL URLWithString:theme.photo_path]];
    myCell.mylabel.text = theme.subject_desc;

    return  myCell;
    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    themeDetailsModel *theme  = [[themeDetailsModel alloc]init];
    theme = self.themePicarr[indexPath.row];
   
   
    NSString *url = [NSString stringWithFormat:@"http://hunliji.com/products/%@.json?user_id=981817",theme.bid];
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]init];
     [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSDictionary *dic = responseObject;
         NSDictionary *tempdic = dic[@"product"];
         self.weburl= tempdic[@"buy_url"];
         Web_themeViewController *web_themeVC = [[Web_themeViewController alloc]init];
         [self.navigationController pushViewController:web_themeVC animated:YES];
         web_themeVC.url=self.weburl;
   
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         
         
     }];
    
}

    
- (void)click:(UIButton *)button{
    
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
    NSString *sandBoxPath = sandBox[0];
    NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"TuiJian.plist"];
    
    self.arr = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
    
    if (self.isArchiver) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已取消收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        
        NSInteger index = 0;
        for (NSInteger i = 0; i < self.arr.count; i++) {
            themeDetailsModel *vie = self.arr[i];
            if ([vie.subject_desc isEqualToString:self.title]) {
                index = i;
                break;
            }
        }
        [self.arr removeObjectAtIndex:index];
        
        // 对已经修改过的数组,再次进行归档操作
        NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
        NSString *sandBoxPath = sandBox[0];
        NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"TuiJian.plist"];
        
        NSLog(@"%@",documentPath);
        
        // 根据对应的路径进行归档操作
        [NSKeyedArchiver archiveRootObject:self.arr toFile:documentPath];
        
        [button setImage:[UIImage imageNamed:@"tubiao2.png"] forState:UIControlStateNormal];
        self.isArchiver = NO;
        
    } else {
        
        NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
        NSString *sandBoxPath = sandBox[0];
        NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"TuiJian.plist"];
        
        if (self.arr != nil) {
            
            [self.arr addObject:self.theme];
        } else {
            self.arr = [NSMutableArray array];
            
            [self.arr addObject:self.theme];
        }
        
        // 根据对应的路径进行归档操作
        [NSKeyedArchiver archiveRootObject:self.arr toFile:documentPath];
        
        self.isArchiver = YES;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        
        [button setImage:[UIImage imageNamed:@"tubiao1.png"] forState:UIControlStateNormal];
        
        
        NSLog(@"%@", documentPath);
        
    }
}
#pragma mark 反归档
- (void)fanguidang{
    
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
    NSString *sandBoxPath = sandBox[0];
    
    // 拼接
    NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"TuiJian.plist"];
    self.arr = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
    
    NSLog(@"%@", documentPath);
    
    self.isArchiver = NO;
    if (self.arr != nil) {
        
        for (themeDetailsModel *vie in self.arr) {
            if ([vie.bid isEqualToString:self.bid]) {
                self.isArchiver = YES;
                break;
            }
        }
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
